package com.dongdongshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.order.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author Eayon
 * @Date 2020/4/4 23:15
 */
@RestController
@RequestMapping("order")
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderService orderService;


    /**
     * 创建订单
     * @param id
     * @param carts
     */
    @PostMapping("/addOrder")
    public DataResult addOrder(@RequestParam("carts") String carts,@RequestParam("id") String id,@RequestParam("user")String user){
        try {
            Long idl = Long.parseLong(id);
            TbUser tbUser = JSONObject.parseObject(user, TbUser.class);
            //需要创建订单的购物车
            List<Cart> cartList = JSON.parseArray(carts, Cart.class);
            orderService.addOrder(cartList,idl,tbUser);
        }catch (Exception e){
            log.error("创建订单异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage());
    }
}
